import sys
from PyQt5.QtWidgets import QApplication
from PyQt5 import QtWidgets, QtCore
from PyQt5.QtWidgets import QWidget, QFileDialog, QMessageBox
from ui import Ui_Form

from trans import wgs84_to_bd09, bd09_to_wgs84


"""
主界面类
"""
class MainWindow(QWidget, Ui_Form):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        
        self.pushButton_wgs84tobaidu.clicked.connect(self.calculation_wgs84tobaidu)
        self.pushButton_baidutowgs84.clicked.connect(self.calculation_baidutowgs84)
        self.pushButton_readme.clicked.connect(self.readme)
        
    '''说明按钮'''
    def readme(self):
        msg_box = QMessageBox(QMessageBox.Warning, '说明', '经纬度格式支持度数和度分秒两种格式，示例：121.446407或121:26:46.6248647(英文冒号)'+'\n'+'转换误差(供参考)：小数点后5位精确，第6位有误差')
        msg_box.exec_()
        
    '''计算按钮_wgs84tobaidu'''
    def calculation_wgs84tobaidu(self):
        lat = decode_degree(self.lineEdit_wgs84lat.text(), 'wgs84纬度')
        lng = decode_degree(self.lineEdit_wgs84lng.text(), 'wgs84经度')
        if lat == None or lng == None:
            return
        result = wgs84_to_bd09(lng, lat)
        self.label_baidulng.setText(str(result[0]))
        self.label_baidulat.setText(str(result[1]))
    
    '''计算按钮_baidutowgs84'''
    def calculation_baidutowgs84(self):
        lat = decode_degree(self.lineEdit_baidulat.text(), '百度纬度')
        lng = decode_degree(self.lineEdit_baidulng.text(), '百度经度')
        if lat == None or lng == None:
            return
        result = bd09_to_wgs84(lng, lat)
        self.label_wgs84lng.setText(str(result[0]))
        self.label_wgs84lat.setText(str(result[1]))
        
    
'''解码经纬度文本'''
def decode_degree(string, name):
    if string == '':
        msg_box = QMessageBox(QMessageBox.Warning, '警告', name +'不能为空！')
        msg_box.exec_()
        return 
    elif ':' in string:
        try:
            string = string.split(':')
            degree = float(string[0]) + float(string[1])/60.0 + float(string[2])/3600.0
        except:
            msg_box = QMessageBox(QMessageBox.Warning, '警告', name +'输入有误！')
            msg_box.exec_()
            return 
    else:
        try:
            degree = float(string)
        except:
            msg_box = QMessageBox(QMessageBox.Warning, '警告', name +'输入有误！')
            msg_box.exec_()
            return 
    return degree
        
if __name__ == "__main__":
    app = QApplication(sys.argv)
    mywin = MainWindow()
    mywin.show()
    sys.exit(app.exec_())
        
